﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System.Reflection;
using FluentNHibernate.Mapping;
using System.Web;
using System.Configuration;
using Abp.Migration;

namespace Abp.NHibernate
{
    public class NhibernateHelper
    {
        public const string WEB = "web";
        public const string THREAD_STATIC = "thread_static";
        private static ISessionFactory sessionFactory = null;

        #region 初始化 生成SessionFactory，并配置上下文策略

        public static void Instance(IPersistenceConfigurer congigurer,
            string currentSessionContextClass = NhibernateHelper.WEB,
            params Assembly[] assemblies)
        {
            /*
            var configuration = Fluently.Configure()
                .Database(congigurer)
            .Mappings(m =>
            {
            foreach (var assembly in assemblies)
            {
                m.FluentMappings.AddFromAssembly(assembly);
                }

            })
            .CurrentSessionContext(currentSessionContextClass)
            .ExposeConfiguration(cfg => new SchemaUpdate(cfg)
                        .Execute(true, true));
                        
                        */
            //configuration.CurrentSessionContext(currentSessionContextClass);
            //configuration.BuildConfiguration();
            //sessionFactory = configuration.BuildSessionFactory();
            List<Type> entityMappers = new List<Type>();
            foreach (var assembly in assemblies)
            {
                entityMappers.AddRange(assembly.GetTypes().Where(type => (!type.IsAbstract)
                     && Abp.Utils.ReflectionUtils.IsAssignableToGenericType(type,typeof(IEntityMapper<>))));
                
            }


            Console.WriteLine("配置子类数量："+entityMappers.Count);
            Console.Read();
        }

        #endregion

        #region Session在当前上下文的操作

        private static void BindContext()
        {
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                CurrentSessionContext.Bind(sessionFactory.OpenSession());
            }
        }

        private static void UnBindContext()
        {
            if (CurrentSessionContext.HasBind(sessionFactory))
            {
                CurrentSessionContext.Unbind(sessionFactory);
            }
        }

        public static void CloseCurrentSession()
        {
            if (sessionFactory.GetCurrentSession().IsOpen)
            {
                sessionFactory.GetCurrentSession().Close();
            }
        }

        public static ISession GetCurrentSession()
        {
            BindContext();
            return sessionFactory.GetCurrentSession();
        }

        #endregion

        #region 关闭SessionFactory（一般在应用程序结束时操作）

        public static void CloseSessionFactory()
        {
            UnBindContext();
            if (!sessionFactory.IsClosed)
            {
                sessionFactory.Close();
            }
        }

        #endregion

        #region 打开一个新的Session

        public static ISession OpenSession()
        {
            return sessionFactory.OpenSession();
        }

        #endregion
    }
}